package com.ncs.cns.activity.fragment;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AbsListView.LayoutParams;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.ncs.cns.R;
import com.ncs.cns.activity.ImagePagerActivity;
import com.ncs.cns.activity.task.AddEventTask;
import com.ncs.cns.business.util.StringUtils;
import com.ncs.cns.framework.Constant;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.display.RoundedBitmapDisplayer;

public class AddEventFragment extends BaseFragment implements OnItemClickListener{
	private final int GRIDVIEW_COLUNM_NUM = 5;
	private final int MAX_PHOTO_NUM = 2;
	private View view;
	private String choose[] = new String[]{"手机相机","从相册选取","取消"};
	//private AlertDialog alertDialog;//让用户选相机还是相册的提示框
	private Dialog alertDialog;
	private Builder waitDialog; 	
	private List<String> photoPaths = new ArrayList<String>();//添加照片的路径list
	private Context context;
	private int imgWidth = 0;
	private int screenWidth = 0;
	private ImageAdapter ia = null;
	private ImageLoader imageLoader = ImageLoader.getInstance();
	private DisplayImageOptions options;
	private String photoPath;
	private SharedPreferences sp;
	private EditText userNameTv;
	private EditText eventContentTv;
	private EditText eventSubjectTv;
	private boolean isSaveDraft = true;
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		view = inflater.inflate(R.layout.activity_add_event, null);	
		init();
		initButton();
		return view;
	}
	//初始化一些点击事件
	private void initButton() {
		view.findViewById(R.id.add_event).setOnClickListener(new OnClickListener() {		
			@Override
			public void onClick(View v) {	
				if(!commService.isNetworkAvailable()){
					Toast.makeText(context, "网络连接错误，请检查网络",Toast.LENGTH_SHORT).show();
					return;
				}
				String subject = eventSubjectTv.getText().toString();
				String content = eventContentTv.getText().toString();
				String userName = userNameTv.getText().toString();			
				boolean flag = validata(subject,content,userName);
				if(!flag)return;
				v.setEnabled(false);				
				Editor editor = sp.edit();
				editor.putString(Constant.USER_NAME_KEY, userName);
				editor.remove(Constant.EVENT_DRAFT_SUBJECT);
				editor.remove(Constant.EVENT_DRAFT_CONTENT);
				editor.commit();
				isSaveDraft = false;
				waitDialog = new AlertDialog.Builder(context);				
				AddEventTask task = new AddEventTask(photoPaths, getActivity(),waitDialog);
				task.execute(subject,content,userName,currentUserId);
			}			
		});
	}
	
	private void init() {	
		sp = view.getContext().getSharedPreferences(Constant.SHAREPATH,
				Context.MODE_PRIVATE);
		userNameTv = (EditText) view.findViewById(R.id.userName);
		eventSubjectTv = (EditText)view.findViewById(R.id.eventTitle);
		eventContentTv = (EditText)view.findViewById(R.id.eventContent);		
		userNameTv.setText(sp.getString(Constant.USER_NAME_KEY, ""));
		eventSubjectTv.setText(sp.getString(Constant.EVENT_DRAFT_SUBJECT, ""));
		eventContentTv.setText(sp.getString(Constant.EVENT_DRAFT_CONTENT, ""));
		context = view.getContext();
		
		options = new DisplayImageOptions.Builder()
		.showStubImage(R.drawable.ic_stub)			// 设置图片下载期间显示的图片
		.showImageForEmptyUri(R.drawable.ic_empty)	// 设置图片Uri为空或是错误的时候显示的图片
		.showImageOnFail(R.drawable.ic_error)		// 设置图片加载或解码过程中发生错误显示的图片	
		.cacheInMemory(true)						// 设置下载的图片是否缓存在内存中
		.cacheOnDisc(true)							// 设置下载的图片是否缓存在SD卡中
		.displayer(new RoundedBitmapDisplayer(20))	// 设置成圆角图片
		.build();									// 创建配置过得DisplayImageOption对象		
		
		DisplayMetrics dm = context.getResources().getDisplayMetrics();
		screenWidth = dm.widthPixels;
		imgWidth = screenWidth/GRIDVIEW_COLUNM_NUM;
		GridView gv = (GridView) view.findViewById(R.id.addImgGridView);
		ia = new ImageAdapter();
		gv.setAdapter(ia);
		gv.setOnItemClickListener(this);
		isSaveDraft = true;
	}
	
	private boolean validata(String subject, String content,
			String userName) {
		if(StringUtils.isEmpty(subject)){
			Toast.makeText(context, "亲，输下标题呗",Toast.LENGTH_SHORT).show();
			return false;
		}else if(StringUtils.isEmpty(content)){
			Toast.makeText(context, "亲，输下内容呗",Toast.LENGTH_SHORT).show();
			return false;
		}else if(StringUtils.isEmpty(userName)){
			Toast.makeText(context, "亲，输下昵称呗",Toast.LENGTH_SHORT).show();
			return false;
		}
		return true;
	}
	
	
	class ImageAdapter extends BaseAdapter{
		private ImageView addImgBtn;
		public ImageAdapter() {
			addImgBtn = new ImageView(context);
			addImgBtn.setTag("Y");
			addImgBtn.setLayoutParams(new LayoutParams(imgWidth,imgWidth));
			addImgBtn.setMaxHeight(imgWidth);
			addImgBtn.setMaxWidth(imgWidth);
			addImgBtn.setAdjustViewBounds(true);
			addImgBtn.setImageResource(R.drawable.add_img);
			addImgBtn.setScaleType(ImageView.ScaleType.FIT_XY);
		}
		
		@Override
		public int getCount() {
			if(photoPaths.size() == MAX_PHOTO_NUM)
				return photoPaths.size() ;
			return photoPaths.size()+1;
		}

		@Override
		public Object getItem(int position) {
			return photoPaths.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			ImageView view;
			if(position == photoPaths.size()){
				 return addImgBtn;
			}else{
				if(convertView == null || (convertView != null && convertView.getTag() != null)){
					view = new ImageView(context);
					view.setLayoutParams(new LayoutParams(imgWidth,imgWidth));
					view.setAdjustViewBounds(true);
					view.setScaleType(ImageView.ScaleType.FIT_XY);
					//view.setImageBitmap(BitmapFactory.decodeFile(photoPaths.get(position)));
				}
				else 
					view = (ImageView)convertView;
				imageLoader.displayImage(Constant.FILE_PREFIX+photoPaths.get(position), view, options);
					
			}
			return view;
		}	
		
		public void reloadImage(){
			this.notifyDataSetChanged();
		}
	}	
	
	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		if(resultCode == Activity.RESULT_CANCELED)return;
		switch(requestCode){
			case 1:
				photoPaths.add(photoPath);
				ia.notifyDataSetChanged();				
			break;		
			case 2:
				Uri uri = data.getData();
				String[] filePathCol = {MediaStore.Images.Media.DATA};
				Cursor cursor = this.getActivity().getContentResolver().query(uri, filePathCol, null, null, null);
				cursor.moveToFirst();
				int inx = cursor.getColumnIndex(filePathCol[0]);
				String path = cursor.getString(inx);
				photoPaths.add(path);
				cursor.close();		
				ia.notifyDataSetChanged();
				break;
			case 3:
				Bundle b = data.getExtras();
				int delImgInx = b.getInt("delImgInx");
				photoPaths.remove(delImgInx);
				ia.notifyDataSetChanged();			
				break;
		}
	}
	
	@Override
	public void onItemClick(AdapterView<?> arg0, View view, int index, long arg3) {
		if(view.getTag() != null && view.getTag().equals("Y")){
			if(alertDialog == null){
				alertDialog = new Dialog(context,R.style.dialogTheme);
				final LayoutInflater inflater = LayoutInflater.from(context);	
				View layout = inflater.inflate(R.layout.photo_dialog, null,false);
				TextView chooseAlbum = (TextView) layout.findViewById(R.id.chooseAlbum);
				TextView chooseCamera = (TextView) layout.findViewById(R.id.chooseCamera);
				TextView chooseCancel = (TextView) layout.findViewById(R.id.chooseCancel);
				chooseAlbum.setOnClickListener(new OnClickListener() {					
					@Override
					public void onClick(View v) {
						Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
						intent.addCategory(Intent.CATEGORY_OPENABLE);
						intent.setType("image/*");
						startActivityForResult(Intent.createChooser(intent, "选择照片"),2);
						alertDialog.dismiss();
					}
				});
				chooseCamera.setOnClickListener(new OnClickListener() {					
					@Override
					public void onClick(View v) {
						Intent intent2 = new Intent(MediaStore.ACTION_IMAGE_CAPTURE, null);
						File path = new File(Environment.getExternalStorageDirectory().getAbsolutePath() +File.separator+"CNSImg"+File.separator);
						if(!path.exists())
							path.mkdirs();	
						File file = new File(path, System.currentTimeMillis()+".jpg");
						photoPath = file.getPath();
						Uri uri = Uri.fromFile(file);
						intent2.putExtra(MediaStore.EXTRA_OUTPUT,uri);
					
						startActivityForResult(intent2,1);	
						alertDialog.dismiss();
					}
				});
				chooseCancel.setOnClickListener(new OnClickListener() {					
					@Override
					public void onClick(View v) {
						alertDialog.dismiss();
					}
				});				
				
				alertDialog.setContentView(layout);
				Window window = alertDialog.getWindow();
				window.setGravity(Gravity.BOTTOM);
				WindowManager.LayoutParams params = window.getAttributes();
				params.width = (int) (screenWidth*0.8);
				RadioGroup radio = (RadioGroup)getActivity().findViewById(R.id.main_tab_group);
				int height = radio.getHeight();
				params.y = height+10;
				window.setAttributes(params);
				window.setWindowAnimations(R.style.dialogStyle);
				alertDialog.show();
//				Builder dialog = new AlertDialog.Builder(context);
//				dialog.setAdapter(new BaseAdapter() {							
//					@Override
//					public View getView(int position, View convertView, ViewGroup parent) {
//						TextView tv;
//						if(convertView == null){
//							tv = new TextView(context);
//							tv.setText(choose[position]);
//							tv.setGravity(Gravity.CENTER);
//							tv.setPadding(0, 5, 0, 5);
//							tv.setTextSize(20);
//							tv.setTextColor(Color.GRAY);
//						}
//						else 
//							tv = (TextView)convertView;
//						tv.setText(choose[position]);
//						return tv;
//					}
//					
//					@Override
//					public long getItemId(int position) {
//						return position;
//					}
//					
//					@Override
//					public Object getItem(int position) {
//						return choose[position];
//					}
//					
//					@Override
//					public int getCount() {
//						return choose.length;
//					}
//				},new DialogInterface.OnClickListener() {							
//					@Override
//					public void onClick(DialogInterface dialog, int which) {							
//						switch(which){
//							case 0:
//								Intent intent2 = new Intent(MediaStore.ACTION_IMAGE_CAPTURE, null);
//								File path = new File(Environment.getExternalStorageDirectory().getAbsolutePath() +File.separator+"CNSImg"+File.separator);
//								if(!path.exists())
//									path.mkdirs();	
//								File file = new File(path, System.currentTimeMillis()+".jpg");
//								photoPath = file.getPath();
//								Uri uri = Uri.fromFile(file);
//								intent2.putExtra(MediaStore.EXTRA_OUTPUT,uri);
//							
//								startActivityForResult(intent2,1);	
//								break;
//							case 1:
//								Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
//								intent.addCategory(Intent.CATEGORY_OPENABLE);
//								intent.setType("image/*");
//								startActivityForResult(Intent.createChooser(intent, "选择照片"),2);									
//								break;										
//							case 2:				
//								break;
//						}
//					}
//				});
//				alertDialog = dialog.create();
			}
			alertDialog.show();
		}else{
			Bundle bundle = new Bundle();
			Intent intent = new Intent(context,ImagePagerActivity.class);
			bundle.putInt("index", index);
			bundle.putStringArrayList("paths",(ArrayList)photoPaths);
			intent.putExtras(bundle);
			startActivityForResult(intent, 3);
		}
	}
	
	@Override
	public void onPause() {
		super.onPause();
		saveDraft();
	}
	
	@Override
	public void onStop() {
		super.onStop();
		saveDraft();
	}
	
	public void saveDraft(){
		if(!isSaveDraft)return;
		String subject = ((TextView)view.findViewById(R.id.eventTitle)).getText().toString();
		String content = ((TextView)view.findViewById(R.id.eventContent)).getText().toString();
		Editor editor = sp.edit();
		editor.putString(Constant.EVENT_DRAFT_SUBJECT, subject ==null ? "":subject);
		editor.putString(Constant.EVENT_DRAFT_CONTENT, content ==null ? "":content);
		editor.commit();	
	}
	
	@Override
	public void setUserVisibleHint(boolean isVisibleToUser) {
		super.setUserVisibleHint(isVisibleToUser);
		
	}
}
